package com.basic.modules.ykf.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.basic.common.exception.RRException;
import com.basic.modules.sys.service.SysConfigService;
import com.basic.modules.ykf.entity.YkfMsgRecordEntity;
import com.basic.modules.ykf.service.SmsService;
import com.basic.modules.ykf.service.YkfMsgRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("smsService")
public class SmsServiceImpl implements SmsService {

    @Autowired
    private YkfMsgRecordService recordService;

    @Autowired
    private SysConfigService configService;


    @Override
    public void sendMsg(String phone, String smsTempCode, Map<String, String> templateParam) throws ClientException {
        String smsTestSign = configService.getValue("SMS_TEST_SIGN");
        if (StrUtil.equals(smsTestSign, "Y")) {
            log.info("使用测试手机号");
            phone = configService.getValue("SMS_TEST_PHONE");
        }
        log.info("phone" + phone);
        log.info("smsTempCode" + smsTempCode);
        log.info("templateParam" + JSONUtil.toJsonStr(templateParam));
        Map<String, String> newTemplateParam = new HashMap<>();
        for (String key : templateParam.keySet()) {
            if (ObjectUtil.isNull(templateParam.get(key))) {
                newTemplateParam.put(key, "-");
            } else {
                newTemplateParam.put(key, templateParam.get(key));
            }
        }
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";                                          //短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";                              //短信API产品域名（接口地址固定，无需修改）
        //TODO 替换成你的AK
        final String accessKeyId = "LTAI5tHUhqioRkJiD1bSh9xy";                              //你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "9ZmIymzTQW2YJPzqWSFeAqNoCfyvZ1";            //你的accessKeySecret，参考本文档步骤2
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,
        // 验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000"
        request.setPhoneNumbers(phone);
        //TODO 必填:短信签名-可在短信控制台中找到  ； 如： 图列的 “京东” 签名，里边就填京东
        request.setSignName("悦来悦好");
        //必填:短信模板-可在短信控制台中找到，是以SMS_xxxxx，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(smsTempCode);
        request.setTemplateParam(JSONUtil.toJsonStr(newTemplateParam));
        //请求失败抛出失败的异常

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("sendSmsResponse:" + JSONUtil.toJsonStr(sendSmsResponse));
        //请求成功打印OK
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            log.info("OK");
            YkfMsgRecordEntity record = new YkfMsgRecordEntity();
            record.setStatus(1);
            record.setMobile(phone);
            record.setMsgTmp(smsTempCode);
            record.setMsgContent(JSONUtil.toJsonStr(newTemplateParam));
            record.setPreSendTime(DateUtil.date());
            record.setSendTime(DateUtil.date());
            record.setRecordTime(DateUtil.date());
            recordService.save(record);
        } else {
            log.error("短信发送失败");
        }
    }

    public static void sendMsg2(String phone, String smsTempCode, Map<String, String> templateParam) throws ClientException {
        log.info("phone" + phone);
        log.info("smsTempCode" + smsTempCode);
        log.info("templateParam" + JSONUtil.toJsonStr(templateParam));
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";                                          //短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";                              //短信API产品域名（接口地址固定，无需修改）
        //TODO 替换成你的AK
        final String accessKeyId = "LTAI5tHUhqioRkJiD1bSh9xy";                              //你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "9ZmIymzTQW2YJPzqWSFeAqNoCfyvZ1";            //你的accessKeySecret，参考本文档步骤2
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,
        // 验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000"
        request.setPhoneNumbers(phone);
        //TODO 必填:短信签名-可在短信控制台中找到  ； 如： 图列的 “京东” 签名，里边就填京东
        request.setSignName("悦来悦好");
        //必填:短信模板-可在短信控制台中找到，是以SMS_xxxxx，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(smsTempCode);
        request.setTemplateParam(JSONUtil.toJsonStr(templateParam));
        //请求失败抛出失败的异常

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("sendSmsResponse:" + JSONUtil.toJsonStr(sendSmsResponse));
        //请求成功打印OK
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            log.info("OK");
        } else {
            throw new RRException("短信发送失败");
        }
    }

    public static void main(String[] args) throws ClientException {
        Map<String, String> map = new HashMap<>();
        map.put("p0", "悦心怡");
        map.put("p1", "丘世贸易");
        map.put("p2", "淘宝");
        map.put("p3", "客服");
        map.put("p4", "2024-02-15");
        map.put("p5", "475");
        map.put("p6", "0");
        sendMsg2("15738859597", "SMS_163620721", map);
    }

}
